package com.itheima.app.manager;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Voice;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.VoiceService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.VoiceVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;

@Component
public class VoiceManager {

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    VoiceService voiceService;

    @Autowired
    FastFileStorageClient client;

    @Autowired
    FdfsWebServer server;

    @Autowired
    RedisTemplate redisTemplate;

    //上传语音
    public void save(MultipartFile soundFile) throws IOException {
        //获取用户id
        Long userId = UserHolder.get().getId();

        //上传文件获取路径
        StorePath soundPath = client.uploadFile(soundFile.getInputStream(), soundFile.getSize(), FileUtil.extName(soundFile.getOriginalFilename()), null);

        Voice voice = new Voice();
        voice.setCreated(System.currentTimeMillis());
        voice.setUserId(userId);
        voice.setVoiceUrl(server.getWebServerUrl() + soundPath.getFullPath());

        voiceService.save(voice);

    }

    //获取语音
    public ResponseEntity findOne() {
        //获取用户id
        Long userId = UserHolder.get().getId();

        Voice voice = voiceService.findOne(userId);

        UserInfo userInfo = userInfoService.findById(voice.getUserId());

        VoiceVo voiceVo = new VoiceVo();
        voiceVo.setUserInfo(userInfo);
        voiceVo.setSoundUrl(voice.getVoiceUrl());

        Integer count = (Integer) redisTemplate.opsForValue().get(UserHolder.get().getId());
        redisTemplate.opsForValue().set(UserHolder.get().getId(),count, Duration.ofSeconds(5));

        if (count == null){
            count = 5;
        }else if (count == 0){
            return ResponseEntity.status(500).body("次数已经用完，明日再来");
        }else {
            --count;
            redisTemplate.opsForValue().set(UserHolder.get().getId(),count);
        }

        voiceVo.setRemainingTimes(count);



        return ResponseEntity.ok(voiceVo);

    }
}
